package com.lapelittle.order.mapper.provider;

import com.lapelittle.order.query.AfterSaleOrderQuery;
import org.apache.ibatis.jdbc.SQL;

public class AfterSaleOrderProvider {
    
    public String queryList(AfterSaleOrderQuery query) {
        SQL sql = new SQL();
        sql.SELECT("a.*, s.merchant_code")
           .FROM("after_sale_order a")
           .LEFT_OUTER_JOIN("sale_order s ON a.order_no = s.order_no");
        
        buildCondition(sql, query);
        
        // 默认按导入时间降序、序号升序排序
        sql.ORDER_BY("a.import_time DESC, a.id ASC");
        
        String sqlStr = sql.toString() + " LIMIT #{offset}, #{pageSize}";
        return sqlStr;
    }
    
    public String queryCount(AfterSaleOrderQuery query) {
        SQL sql = new SQL();
        sql.SELECT("COUNT(*)")
           .FROM("after_sale_order a")
           .LEFT_OUTER_JOIN("sale_order s ON a.order_no = s.order_no");
        
        buildCondition(sql, query);
        
        return sql.toString();
    }
    
    private void buildCondition(SQL sql, AfterSaleOrderQuery query) {
        if (query.getShopName() != null && !query.getShopName().isEmpty()) {
            sql.WHERE("shop_name LIKE CONCAT('%', #{shopName}, '%')");
        }
        
        if (query.getStatus() != null && !query.getStatus().isEmpty()) {
            sql.WHERE("a.status = #{status}");
        }
        
        if (query.getKeyword() != null && !query.getKeyword().isEmpty()) {
            sql.WHERE("(a.after_sale_no LIKE CONCAT('%', #{keyword}, '%') " +
                    "OR a.order_no LIKE CONCAT('%', #{keyword}, '%'))");
        }
        
        if (query.getStartTime() != null && !query.getStartTime().isEmpty()) {
            sql.WHERE("DATE(a.import_time) >= #{startTime}");
        }
        
        if (query.getEndTime() != null && !query.getEndTime().isEmpty()) {
            sql.WHERE("DATE(a.import_time) <= #{endTime}");
        }
    }
}